﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;

namespace Eneta.Portal.Forum.Common.Controls
{
    public class OWSSubmitButton : WebControl, IPostBackEventHandler
    {
        // Events
        public event EventHandler Click;

        // Methods
        private void EmitProcessFormScript()
        {
            if (!this.Page.IsClientScriptBlockRegistered("OWSProcessFormScript"))
            {
                this.Page.RegisterStartupScript("OWSProcessFormScript", "<script> \r\nfunction ProcessOwsForm(ctl, argument) \r\n{ \r\n    if (frm.fPreviewMode) \r\n    { \r\n        var L_cantSave_Text = \"This form cannot be saved when previewing this page.\"; \r\n        window.alert(L_cantSave_Text); \r\n        return; \r\n    } \r\n    if (frm.FValidate(true)) \r\n    { \r\n        frm.FPostProcess(); \r\n        __doPostBack(ctl, argument); \r\n    } \r\n} \r\n</script>");
                this.Page.GetPostBackEventReference(this);
            }
        }

        protected virtual void OnClick(EventArgs e)
        {
            if (this.Click != null)
            {
                this.Click(this, e);
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            this.EmitProcessFormScript();
            base.OnLoad(e);
        }

        public void RaisePostBackEvent(string eventArgument)
        {
            this.OnClick(EventArgs.Empty);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            switch (this.ButtonType)
            {
                case OWSButtonType.Button:
                    writer.Write("<input type=\"button\" class=\"{0}\" onclick=\"{1}\" value=\"{2}\" />", this.CssClass, string.Format("ProcessOwsForm('{0}', 'Click');", this.UniqueID), SPEncode.HtmlEncode(this.Text));
                    return;

                case OWSButtonType.HyperLink:
                    writer.Write("<a class=\"{0}\" href=\"{1}\" >{2}</a>", this.CssClass, string.Format("javascript:ProcessOwsForm('{0}', 'Click');", this.UniqueID), SPEncode.HtmlEncode(this.Text));
                    return;
            }
        }

        // Properties
        public OWSButtonType ButtonType
        {
            get
            {
                if (this.ViewState["ButtonType"] == null)
                {
                    this.ButtonType = OWSButtonType.HyperLink;
                }
                return (OWSButtonType)this.ViewState["ButtonType"];
            }
            set
            {
                this.ViewState["ButtonType"] = value;
            }
        }

        public string Text
        {
            get
            {
                return ("" + this.ViewState["Text"]);
            }
            set
            {
                this.ViewState["Text"] = value;
            }
        }
    }

}
